package com.supplychainapi.filter;

import com.supplychainapi.domain.LoginCache;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 参数添加
 */
@Component
public class SessionResolver extends WebMvcConfigurerAdapter {
    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
        argumentResolvers.add(new HandlerMethodArgumentResolver() {
            @Override
            public boolean supportsParameter(MethodParameter parameter) {
                Class  parameterType = parameter.getParameterType();
                return parameterType.equals(LoginCache.class);
            }

            @Override
            public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
                Object request = webRequest.getNativeRequest();
                HttpServletRequest httpServletRequest = (HttpServletRequest) request;
                LoginCache cache = (LoginCache) httpServletRequest.getAttribute("userInfo");
                return cache;
            }
        });
        super.addArgumentResolvers(argumentResolvers);
    }
}
